/**
* Ejemplo RSS
* Applicast(tm) Widget
*
* (c) 2009 ILERRED, S.L.
*/

var Titulares = {
  MAX_ITEMS: 30,

  channel: {
    url: '',
    title: '',
    itemListing: []
  }
};

var Widget = Class.create({
  initialize: function() {
    this.assetsPath = './assets/';

    this.options = {
      source: 'http://www.elpais.com/rss.html'
    };

    this.stateNodes = [$('state-error'), $('state-loading'), $('state-normal'), $('state-active')];
    this.view = null;

    Event.observe('keypress', this.onKeyPress.bind(this));
    Event.observe('modechange', this.onModeChange.bind(this));

    this.getItemListing();
  },

  changeMode: function(newMode) {
    this.currentMode = newMode;
    this.setupComponent(newMode);
    this.showComponent(newMode);
  },

  showComponent: function(index) {
    if ( index < 0 || index >= this.stateNodes.length ) return;

    for(var i=0, m=this.stateNodes.length; i < m; ++i) {
      if ( i == index )
        this.stateNodes[i].setVisible(true);
      else
        this.stateNodes[i].setVisible(false);
    }
  },

  setupComponent: function(index) {
    if ( index < 0 || index >= WidgetModes.length ) return;

    switch(WidgetModes[index]) {
      case 'Error':
        $('bg-error').loadImage(this.assetsPath + 'backgrounds/bg-error.png');
        break;

      case 'Loading':
        $('bg-loading').loadImage(this.assetsPath + 'backgrounds/bg-normal.png');
          $('widget-logo').loadImage(this.assetsPath + 'icons/icono.png');
          $('text-loading').setStr('Cargando', true, {color: 'aaaaaa'});
        break;

      case 'Normal/Focus':
        $('bg-normal').loadImage(this.assetsPath + 'backgrounds/bg-normal.png');
        $('img-onscreen-help').setVisible(false);
        $('img-source-logo').loadImage(this.assetsPath + 'icons/elpais.png');
        $('text-header-normal').setStr(Titulares.channel.title);

        $('item-normal-selected-1').loadImage(this.assetsPath + 'backgrounds/hover-bar.png');
        $('item-normal-selected-2').loadImage(this.assetsPath + 'backgrounds/hover-bar.png');
        $('item-normal-selected-3').loadImage(this.assetsPath + 'backgrounds/hover-bar.png');

        $('up-arrow-normal').loadImage(this.assetsPath + 'scroll/up.png');
        $('down-arrow-normal').loadImage(this.assetsPath + 'scroll/down.png');
        break;

      case 'Active':
        var now = new Date();

        $('bg-active').loadImage(this.assetsPath + 'backgrounds/bg-active.png');

        $('up-arrow-active').loadImage(this.assetsPath + 'scroll/up-active.png');
        $('down-arrow-active').loadImage(this.assetsPath + 'scroll/down-active.png');

        $('img-source-logo-active').loadImage(this.assetsPath + 'icons/elpais.png');
        $('text-header-active').setStr(DateUtil.toLongDateString(now));

        $('text-pubdate-active').setStr(this.currentItem.date);
        $('text-title-active').setStr(this.currentItem.title);
        break;
    }
  },

  getItemListing: function() {
    this.changeMode(WidgetMode.LOADING);
    new Ajax.Request(this.options.source, {
      onSuccess: function(t) {
        $('text-loading').setStr('Procesando', true, {color: 'aaaaaa'});
        try {
          var xml = t.responseXML;
          this.parseItems(xml);
          this.view = new HeadlinesView({
            maxElements: 3,
            sourceList: Titulares.channel.itemListing
          });
          this.view.first();
          this.changeMode(WidgetMode.NORMALFOCUS);
        } catch(e) {
          print(String(e));
          this.changeMode(WidgetMode.ERROR);
        }
      }.bind(this),
      onFailure: function(t) {
        this.changeMode(WidgetMode.ERROR);
      }.bind(this),
      onException: function(t) {
        this.changeMode(WidgetMode.ERROR);
      }.bind(this)
    });
  },

  parseItems: function(xml) {
    if ( !xml )
      throw 'Invalid XML Response!';

    if ( XMLUtil.responseIsError(xml) )
      throw 'Response is an error message!';

    // Clean up
    Titulares.channel.url = '';
    Titulares.channel.title = '';
    Titulares.channel.itemListing.clear();

    var root = XMLUtil.getNode(xml, 'channel');
    if ( !root )
      throw 'No root node detected!';

    // Get channel title & url
    Object.extend(Titulares.channel, XMLUtil.getChildrenValues(root, ['title', 'link']) || { });

    // Items
    var items = XMLUtil.getNode(root, 'item');
    if ( items.empty() )
      throw 'No items found!';
    for (var i=0, m=items.length; i < m && i < Titulares.MAX_ITEMS; ++i) {
      var currentItem = items[i];

      Titulares.channel.itemListing.push({
        title: XMLUtil.getNodeValue(currentItem, 'title') || '',
        text: XMLUtil.getNodeValue(currentItem, 'description') || '',
        date: XMLUtil.getNodeValue(currentItem, 'pubDate') || '',
        author: XMLUtil.getNodeValue(currentItem, 'author') || ''
      });
    }
  },

  onKeyPress: function(e) {
    if ( !e ) return;

    switch( e.keyCode ) {
      case Event.KEY_DOWN:
        if ( WidgetModes[this.currentMode] == 'Normal/Focus' && this.view )
          this.view.next();
        else if ( WidgetModes[this.currentMode] == 'Active' && this.scrollerComponent )
          this.scrollerComponent.pageDown();
        break;

      case Event.KEY_RIGHT:
        if ( WidgetModes[this.currentMode] == 'Normal/Focus' && this.view )
          this.view.next();
        break;

      case Event.KEY_UP:
        if ( WidgetModes[this.currentMode] == 'Normal/Focus' && this.view )
          this.view.prev();
        else if ( WidgetModes[this.currentMode] == 'Active' && this.scrollerComponent )
          this.scrollerComponent.pageUp();
        break;

      case Event.KEY_LEFT:
        if ( WidgetModes[this.currentMode] == 'Normal/Focus' && this.view )
          this.view.prev();
        break;
    }
  },

  onModeChange: function(e) {
    if ( !e ) return;

    switch( WidgetModes[e.mode] ) {
      case 'Normal/Focus':
        if ( e.focus && this.view )
          this.view.enable();
        else if ( !e.focus && this.view )
          this.view.disable();
        break;

      case 'Active':
        this.changeMode(WidgetMode.LOADING);
        this.currentItem = this.view.getSelected();
        this.scrollerComponent = new NewsContentScroller('text-description-active', 
          String(this.currentItem.text).stripTags(), {
          linesPerPage: 15
        });
        this.changeMode(WidgetMode.ACTIVE);
        break;
    }
  }
});

var HeadlinesView = Class.create(ListView, {
  initialize: function($super, options) {
    $super(options);
    this.focused = false;
  },

  highlightSelected: function() {
    // Unselect all
    for (var i=0, m=this.max; i < m; ++i) {
      $('item-normal-' + (i+1)).setAlpha(180);
      $('item-normal-selected-' + (i+1)).setVisible(false);
    }

    if ( this.focused ) {
      $('item-normal-selected-' + (this.move+1)).setVisible(true);
      $('item-normal-' + (this.move+1)).setAlpha(255);
    }
  },

  show: function(start) {
    // Index control
    var boundedStart = start;
    if ( boundedStart < 0 )
      boundedStart = 0;
    else {
      if ( (boundedStart+this.max) > this.size )
        boundedStart = this.size - this.max;
    }

    var limit = this.max;
    if ( this.size < limit ) {
      boundedStart = 0;
      limit = this.size;
    }

    // Hide all theater components
    for (var i=1; i <= this.max; ++i)
      $('item-normal-' + i).setVisible(false);

    // Enter info & show
    for(var i=0, k=boundedStart; i < limit; ++i, ++k) {
      $('text-title-normal-' + (i+1)).setStr(this.list[k].title);
      $('text-pubdate-normal-' + (i+1)).setStr(this.list[k].date);
      $('item-normal-' + (i+1)).setVisible(true);
    }

    // Scrolling
    if ( this.focused ) {
      $('up-arrow-normal').setVisible((boundedStart > 0 ? true : false));
      $('down-arrow-normal').setVisible(((this.size > this.max && (boundedStart+this.max) < this.size) ? true : false));
    } else {
      $('up-arrow-normal').setVisible(false);
      $('down-arrow-normal').setVisible(false);
    }
  },

  enable: function() {
    this.focused = true;
    this.moveToIndex(this.selected);
  },

  disable: function() {
    this.focused = false;
    this.moveToIndex(this.selected);
  }
});

var NewsContentScroller = Class.create(MemoPageScroller, {
  initialize: function($super, textNode, text, options) {
    $super(textNode, text, options);
  },

  updateScrollBars: function() {
    $('up-arrow-active').setVisible(false);
    $('down-arrow-active').setVisible(false);

    if ( this.currentPage > 0 )
      $('up-arrow-active').setVisible(true);

    if ( this.currentPage < this.pages-1 )
      $('down-arrow-active').setVisible(true);
  }
});